"""
对话管理API端点
"""

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.services.conversation_service import ConversationService
from app.schemas.conversation import (
    ConversationCreate, ConversationUpdate, ConversationResponse,
    ConversationWithMessages, ConversationSummary, UpdateTitleRequest
)
from app.core.logging_config import get_logger
# 导入认证依赖
from app.api.v1.endpoints.auth import get_current_user
from app.models.user import User

router = APIRouter()
conversation_service = ConversationService()
logger = get_logger(__name__)


@router.get("", response_model=List[ConversationResponse])
async def get_conversations(
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取对话列表"""
    try:
        user_id = current_user.id
        
        conversations = conversation_service.get_user_conversations(
            db=db,
            user_id=user_id,
            skip=skip,
            limit=limit
        )
        
        # 转换为响应模型，确保 last_message_at 字段被正确填充
        return [ConversationResponse.model_validate(conv) for conv in conversations]
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话列表失败: {str(e)}")


@router.get("/{conversation_id}", response_model=ConversationWithMessages)
async def get_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取对话详情"""
    try:
        user_id = current_user.id
        
        conversation = conversation_service.get_conversation_with_messages(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not conversation:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        return conversation
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话详情失败: {str(e)}")


@router.post("/", response_model=ConversationResponse)
async def create_conversation(
    conversation: ConversationCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建新对话"""
    try:
        logger.info(f"收到创建对话请求: 用户ID={current_user.id}, 标题={conversation.title}, 模型ID={conversation.model_config_id}")
        
        user_id = current_user.id
        
        new_conversation = conversation_service.create_conversation(
            db=db,
            user_id=user_id,
            title=conversation.title,
            model_config_id=conversation.model_config_id,
            knowledge_base_id=conversation.knowledge_base_id,
            prompt_template_id=conversation.prompt_template_id
        )
        
        logger.info(f"对话创建成功: 对话ID={new_conversation.id}, 标题={new_conversation.title}")
        return ConversationResponse.model_validate(new_conversation)
        
    except Exception as e:
        logger.error(f"创建对话失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"创建对话失败: {str(e)}")


@router.put("/{conversation_id}", response_model=ConversationResponse)
async def update_conversation(
    conversation_id: int,
    conversation_update: ConversationUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新对话"""
    try:
        user_id = current_user.id
        
        # 检查对话是否存在
        existing_conversation = conversation_service.get_conversation_with_messages(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not existing_conversation:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        updated_conversation = conversation_service.update(
            db=db,
            db_obj=existing_conversation,
            obj_in=conversation_update
        )
        
        return ConversationResponse.model_validate(updated_conversation)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新对话失败: {str(e)}")


@router.put("/{conversation_id}/title")
async def update_conversation_title(
    conversation_id: int,
    request: UpdateTitleRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新对话标题"""
    try:
        user_id = current_user.id
        
        logger.info(f"更新对话标题: conversation_id={conversation_id}, title='{request.title}'")
        
        success = conversation_service.update_conversation_title(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id,
            title=request.title
        )
        
        if not success:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        logger.info(f"对话标题更新成功: conversation_id={conversation_id}")
        return {"message": "标题更新成功", "title": request.title}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新对话标题失败: conversation_id={conversation_id}, error={str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"更新对话标题失败: {str(e)}")


@router.put("/{conversation_id}/prompt-template")
async def update_conversation_prompt_template(
    conversation_id: int,
    request: dict,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新对话的提示词模板"""
    try:
        user_id = current_user.id
        
        # 检查对话是否存在
        existing_conversation = conversation_service.get_conversation_with_messages(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not existing_conversation:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        # 从请求中获取提示词模板ID
        prompt_template_id = request.get("prompt_template_id")
        if not prompt_template_id:
            raise HTTPException(status_code=400, detail="缺少提示词模板ID")
        
        # 验证提示词模板是否存在
        from app.services.prompt_service import PromptService
        prompt_service = PromptService()
        prompt_template = prompt_service.get(db=db, id=prompt_template_id)
        
        if not prompt_template:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        # 更新对话的提示词模板
        existing_conversation.prompt_template_id = prompt_template_id
        db.commit()
        db.refresh(existing_conversation)
        
        logger.info(f"对话 {conversation_id} 的提示词模板已更新为: {prompt_template_id}")
        
        return {
            "message": "提示词模板更新成功",
            "prompt_template_id": prompt_template_id,
            "prompt_template_name": prompt_template.name
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新对话提示词模板失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"更新提示词模板失败: {str(e)}")


@router.delete("/{conversation_id}")
async def delete_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除对话"""
    try:
        user_id = current_user.id
        
        success = conversation_service.delete_conversation(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not success:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        return {"message": "对话删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除对话失败: {str(e)}")


@router.post("/{conversation_id}/archive")
async def archive_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """归档对话"""
    try:
        user_id = current_user.id
        
        success = conversation_service.archive_conversation(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not success:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        return {"message": "对话归档成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"归档对话失败: {str(e)}")


@router.get("/{conversation_id}/summary", response_model=ConversationSummary)
async def get_conversation_summary(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取对话摘要"""
    try:
        user_id = current_user.id
        
        conversation = conversation_service.get_conversation_with_messages(
            db=db,
            conversation_id=conversation_id,
            user_id=user_id
        )
        
        if not conversation:
            raise HTTPException(status_code=404, detail="对话不存在")
        
        messages = conversation_service.get_conversation_messages(
            db=db,
            conversation_id=conversation_id
        )
        
        summary = ConversationSummary(
            id=conversation.id,
            title=conversation.title,
            message_count=conversation.message_count,
            created_at=conversation.created_at,
            updated_at=conversation.updated_at,
            last_message_at=conversation.updated_at,  # 添加最后消息时间
            model_name=conversation.model_config.name if conversation.model_config else None,
            knowledge_base_name=conversation.knowledge_base.name if conversation.knowledge_base else None,
            prompt_template_name=conversation.prompt_template.name if conversation.prompt_template else None,
            recent_messages=[
                {
                    "role": msg.role,
                    "content": msg.content[:100] + "..." if len(msg.content) > 100 else msg.content,
                    "created_at": msg.created_at
                }
                for msg in messages[-5:]  # 最近5条消息
            ]
        )
        
        return summary
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话摘要失败: {str(e)}")
